import { constantRoutes } from '@/router'
import Layout from '@/layout/index'
// const _import = require("@/router/dev.js")

/**
* 接口返回的菜单数据拼装成路由格式的数据
* @param list 处理的路由列表
*/
export function AddMenuRoutes(list = []) {
  const newRoutes = []
  list.map((v, i) => {
    const { path, name, component, redirect, title, icon, children, meta, hidden } = v

    const route = {
      path: component == '#' && i == 0 ? path : path
    }

    if (component && component == '#') {
      route.component = Layout
    } else {
      // route.component = _import(component)

      /*
                解析返回的路由信息时import(‘@/views/XXX/index.vue’) 会报错，找不到。
                开始把整个路由信息’@/views/XXX/index.vue’全部返回，直接使用require([/${component}], resolve)) ，还是报错；

                搜索尝试后解决component只要中间部分：
                eg: `@/views/RetrievePassword/index.vue' => 'RetrievePasswod'
                解析时：require([`@/views/${component}/index.vue`], resolve))
            */
      // route.component = (resolve) => require([`@/views/${component}/index.vue`], resolve)
      route.component = (resolve) => require([`@/views/${component}`], resolve)
    }

    if (name) {
      route.name = name
    }
    if (hidden) {
      route.hidden = hidden
    }

    if (meta) {
      route.meta = meta
    }
    if (title) {
      // Vue.set(route, 'meta', { title })
      route.meta = {
        title
      }
      if (icon) {
        Object.assign(route.meta, { icon })
      }
    }

    if (redirect) {
      // Vue.set(route, 'redirect', redirect)
      route.redirect = redirect
    }

    if (children && children.length) {
      route.children = []
      route.children = AddMenuRoutes(v.children)
    }
    newRoutes.push(route)
  })
  return newRoutes
}

const state = {
  routes: [], // 常量路由
  addRoutes: []// 动态路由
}

const mutations = {
  // 存储路由数据
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

const actions = {
  /**
    * @param {*} permissionList 后台传回来的路由数据
    */
  async generateRoutes({ commit }, permissionList) {
    const MenuList = []
    const permissions = permissionList || []

    // 深拷贝
    Object.assign(MenuList, permissions)

    const newRoutes = await AddMenuRoutes(MenuList)

    commit('SET_ROUTES', newRoutes)
    return newRoutes
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

